<template>
	<view class="orderPlace-container">
		<orderHeader :headerData="orderGrabbingData" :showActivitiesTime="false" :showActivitiesDistance="false"
			:showActivitiesCopyBtn="false">
		</orderHeader>

		<view class="order-card m-t-20 m-b-20">
			<uni-collapse>
				<uni-collapse-item titleBorder="none" :open="['0','1','2','3'].includes(orderGrabbingData.orderStatus)">
					<template v-slot:title>
						<view class="u-flex u-flex-items-center">
							<view class="order-card-title orderplace-title m-t-10 m-b-10">1.进店下单,回填单号 </view>
							<u-count-down :time="orderGrabbingData.expirationMillisecond" format="HH:mm:ss" autoStart
								@change="onChangePlaceOrder" v-if="orderGrabbingData.orderStatus === '0'">
								<view class="u-flex time" v-if="timeData">
									<view class="time__custom">
										<text
											class="time__custom__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}</text>
									</view>
									<text class="time__doc">:</text>
									<view class="time__custom">
										<text
											class="time__custom__item">{{ timeData.minutes>10?timeData.minutes:'0'+timeData.minutes }}</text>
									</view>
									<text class="time__doc">:</text>
									<view class="time__custom">
										<text
											class="time__custom__item">{{ timeData.seconds>10?timeData.seconds:'0'+timeData.seconds }}</text>
									</view>
								</view>
							</u-count-down>
						</view>
					</template>
					<view class="placeorder-content">
						<view class="u-flex u-flex-items-center m-t-20 m-b-20 placeorder-title">
							<view class="title-index">1</view>领取红包，锁定名额
						</view>
						<view class="u-flex m-b-20">
							<u-button type="primary" shape="circle" text="立即领取外卖红包" color="#FF5151"
								@tap="jumpExternalLinks(orderGrabbingData,'hb')"></u-button>
						</view>

						<view class="u-flex u-flex-items-center m-t-20 m-b-20 placeorder-title">
							<view class="title-index">2</view>快捷进店下单
						</view>
						<view class="u-flex m-b-20">
							<u-button type="primary" :hairline="false" shape="circle" text="一键进店下单" color="#FF5151"
								plain @tap="jumpExternalLinks(orderGrabbingData,'jd')"></u-button>
						</view>


						<view class="teile m-t-10">
							<view class="u-flex placeorder-title m-b-20">
								<view class="title-index">3</view>提交订单号
							</view>
							<view class="placeorder-2-main">
								<view class="m-b-20">
									需要在<text class="prompt-color">报名后3小时内</text>提交，<text
										class="prompt-color">超时视为自动放弃活动</text>
								</view>
								<view class="u-flex u-flex-between m-b-20">
									<view class="u-flex">
										外卖订单号
									</view>
									<view @tap="popScreenshotexample=true" class="prompt-color placeorder-2-main-text">
										如何获取外卖订单号?</view>
								</view>
								<view class="m-b-20">
									<u-input placeholder="请输入外卖订单号" border="surround"
										v-model="orderGrabbingData.orderNumber"></u-input>
								</view>
								<view class="m-b-20">
									<u-button :disabled="!orderGrabbingData.orderNumber" type="primary" shape="circle"
										text="确认提交订单号" color="#FE791B"
										v-if="!['2','3'].includes(orderGrabbingData.orderStatus)"
										@tap="postUploadOrderNumber"></u-button>
								</view>

							</view>
						</view>

					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>

		<view class="order-card m-t-20 m-b-20">
			<uni-collapse>
				<uni-collapse-item titleBorder="none" :open="['1','2','3'].includes(orderGrabbingData.orderStatus)"
					:disabled="orderGrabbingData.orderStatus === '0'">
					<template v-slot:title>
						<view class="u-flex u-flex-items-center">
							<view class="order-card-title orderplace-title m-t-10 m-b-10">2.上传用餐凭证和反馈截图 </view>
							<!-- -->
							<u-count-down v-if="orderGrabbingData.orderStatus === '1'"
								:time="orderGrabbingData.expirationMillisecond" format="HH:mm:ss" autoStart millisecond
								@change="onChangePlaceOrder">
								<view class="u-flex time" v-if="timeData">
									<view class="time__custom">
										<text
											class="time__custom__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}</text>
									</view>
									<text class="time__doc">:</text>
									<view class="time__custom">
										<text
											class="time__custom__item">{{ timeData.minutes>10?timeData.minutes:'0'+timeData.minutes }}</text>
									</view>
									<text class="time__doc">:</text>
									<view class="time__custom">
										<text
											class="time__custom__item">{{ timeData.seconds>10?timeData.seconds:'0'+timeData.seconds }}</text>
									</view>
								</view>
							</u-count-down>
						</view>
					</template>
					<view class="uploading-content">
						<view>
							<view class="u-flex u-flex-between u-flex-items-center m-t-20 m-b-20 uploading-title">
								<view class="uploading-title-text">订单完成截图</view>
								<view class="">
									<u-button type="primary" :hairline="false" size="small" shape="circle" text="快捷截图"
										color="#FF5151" plain
										@tap="jumpExternalLinks(orderGrabbingData,'dd')"></u-button>
								</view>
							</view>
							<view class="uploading-warn">
								已完成字样+店铺名+实付金额+订单号+下单时间
							</view>

							<view class="m-t-20">
								<u-upload :fileList="orderComplete.confirmImage" @afterRead="handleConfirmAfter"
									@delete="handleConfirmDet" name="1" :previewFullImage="true" :maxCount="5"
									width="200rpx" height="200rpx">
									<image :src="getimageUrl('addimage.png')" class="upload_imgs_img">
									</image>
								</u-upload>
							</view>
						</view>

						<view v-if="orderGrabbingData.completeRequire !== 'noFeedback'">
							<view class="u-flex u-flex-between u-flex-items-center m-t-10 m-b-20 uploading-title">
								<view class="uploading-title-text">反馈截图</view>
								<view>
									<u-button type="primary" :hairline="false" size="small" shape="circle" text="快捷截图"
										color="#FF5151" plain
										@tap="jumpExternalLinks(orderGrabbingData,'fk')"></u-button>
								</view>
							</view>
							<view class="uploading-warn">
								<view class="m-b-10"><text
										class="uploading-warn-lable">要求</text>（{{orderGrabbingData.evaluateNumber}}字好评+{{orderGrabbingData.evaluationMap}}图）
								</view>
								<view v-if="orderGrabbingData.remark">
									<text class="uploading-warn-lable">备注</text>&emsp;{{orderGrabbingData.remark}}
								</view>
							</view>

							<view class="m-t-20">
								<u-upload width="200rpx" height="200rpx" :fileList="orderComplete.goodReviews"
									@afterRead="handlegoodReviewsAfter" @delete="handlegoodReviewsDet" name="1"
									:previewFullImage="true" :maxCount="5">
									<image :src="getimageUrl('addimage.png')" class="upload_imgs_img">
									</image>
								</u-upload>
							</view>
						</view>

						<view class="m-b-20 m-t-20">
							<u-button v-if="!['2','3'].includes(orderGrabbingData.orderStatus)" type="primary"
								shape="circle" text="确认提交" color="#FE791B" @tap="postUploadOrderScreenshot"></u-button>

							<u-button v-else type="primary" shape="circle" text="确认提交" color="#FE791B"
								@tap="postEditWfActivityOrder"></u-button>
						</view>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>

		<u-popup :show="popScreenshotexample" :round="'20rpx'" mode="center" @close="popScreenshotexample=false"
			:closeable="true">
			<view class="screenshot-example" v-if="popScreenshotexample">
				<view class="screenshot-example-title">温馨提示</view>
				<img style="width: 400rpx;height: 400rpx;" :src="getimageUrl('screenshotexample.gif')" />
			</view>
		</u-popup>
	</view>
</template>

<script setup lang="ts">
	import { reactive, ref, unref, getCurrentInstance } from "vue";
	import { onLoad } from '@dcloudio/uni-app';
	import orderHeader from '@/components/orderHeader.vue';
	import { upload } from '@/common/sys.api';
	import { wfActivityOrderQueryById, uploadOrderNumber, uploadOrderScreenshot, editWfActivityOrder } from '@/common/order.api';
	import { getimageUrl } from '@/util/util.js';
	const { proxy } = getCurrentInstance();
	let popScreenshotexample = ref(false)
	let timeData = ref({ hours: 0, minutes: 0, seconds: 0 })
	// let orderNum = ref('')
	let orderComplete = reactive({
		confirmImage: [],
		goodReviews: [],
	})

	let orderGrabbingData = ref({
		shopName: '',
		orderNumber: '',
		id: '',
		remark: '',
		orderStatus: '',
		platformAuditStatus: '',
		merchantAuditStatus: '',
		expirationMillisecond: '',
		evaluateNumber: '',
		evaluationMap: '',
	})
	let orderId = ''

	function onChangePlaceOrder(e) {
		timeData.value = e
	}

	onLoad(async (option) => {
		orderId = option.id
		orderGrabbingDataInit(orderId)
	})

	async function orderGrabbingDataInit(orderId) {
		let res = await wfActivityOrderQueryById({ id: orderId, latitude: unref(proxy['vuex_current_position']).location.lat, longitude: unref(proxy['vuex_current_position']).location.lng })
		orderGrabbingData.value = res
		orderComplete.confirmImage = res.confirmImage ? res.confirmImage.split(',').map(item => { return { url: item } }) : []
		orderComplete.goodReviews = res.goodReviews ? res.goodReviews.split(',').map(item => { return { url: item } }) : []
	}

	async function postUploadOrderNumber() {
		if (!unref(orderGrabbingData).orderNumber) {
			return uni.showToast({
				icon: 'none',
				title: '请输入订单号！'
			})
		}

		await uploadOrderNumber({ id: unref(orderGrabbingData).id, orderNumber: unref(orderGrabbingData).orderNumber })
		await orderGrabbingDataInit(orderId)
		await uni.showToast({
			title: '提交订单号成功！'
		})
	}

	async function postUploadOrderScreenshot() {
		if (!unref(orderComplete).confirmImage.length) {
			return uni.showToast({
				icon: 'none',
				title: '请上传订单完成截图！'
			})
		}

		const params = {
			id: unref(orderGrabbingData).id,
			confirmImage: unref(orderComplete).confirmImage?.map(item => item?.url)?.join(','),
			goodReviews: unref(orderComplete).goodReviews?.map(item => item?.url)?.join(','),
		}

		unref(orderComplete).confirmImage
		await uploadOrderScreenshot(params)
		await orderGrabbingDataInit(orderId)
		await uni.showToast({
			// icon: 'none',
			title: '上传成功！'
		})
		uni.navigateBack({
			delta: 1
		});
	}

	async function postEditWfActivityOrder() {
		if (unref(orderGrabbingData).orderNumber === '') {
			return uni.showToast({
				icon: 'none',
				title: '请输入订单号！'
			})
		}

		if (!unref(orderComplete).confirmImage.length) {
			return uni.showToast({
				icon: 'none',
				title: '请上传订单完成截图！'
			})
		}

		const params = {
			id: unref(orderGrabbingData).id,
			orderNumber: unref(orderGrabbingData).orderNumber,
			confirmImage: unref(orderComplete).confirmImage?.map(item => item?.url)?.join(','),
			goodReviews: unref(orderComplete).goodReviews?.map(item => item?.url)?.join(','),
			platformAuditStatus: null,
			merchantAuditStatus: null
		}

		if (unref(orderGrabbingData).orderStatus === '2') {
			if (unref(orderGrabbingData).platformAuditStatus === '3') {
				params.platformAuditStatus = '1'
			}
		}

		if (unref(orderGrabbingData).orderStatus === '3') {
			if (unref(orderGrabbingData).merchantAuditStatus === '3') {
				params.merchantAuditStatus = '1'
			}
		}
		editWfActivityOrder(params)
		await orderGrabbingDataInit(orderId)
		await uni.showToast({
			// icon: 'none',
			title: '提交成功！'
		})
		uni.navigateBack({
			delta: 1
		});

	}


	/**
	 * 确认图片
	 */
	async function handleConfirmAfter(event) { // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = orderComplete.confirmImage.length;
		lists.map((item) => {
			orderComplete.confirmImage.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await upload({ filePath: lists[i].url, name: 'file', custom: { toast: false } });
			let item = orderComplete.confirmImage[fileListLen];
			orderComplete.confirmImage.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	}

	/**
	 * 确认图片
	 */
	function handleConfirmDet(event) {
		orderComplete.confirmImage?.splice(event.index, 1);
	}

	/**
	 * 确认图片
	 */
	async function handlegoodReviewsAfter(event) { // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = orderComplete.goodReviews.length;
		lists.map((item) => {
			orderComplete.goodReviews.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await upload({ filePath: lists[i].url, name: 'file', custom: { toast: false } });
			let item = orderComplete.goodReviews[fileListLen];
			orderComplete.goodReviews.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	}

	/**
	 * 确认图片
	 */
	function handlegoodReviewsDet(event) {
		orderComplete.goodReviews?.splice(event.index, 1);
	}

	function jumpExternalLinks(item, type) {

		let genderMapEle = {
			'hb': 'ele-recommend-price/pages/guest/index?inviterId=11c88891&chInfo=ch_wechat_chsub_CopyLink&_ltracker_f=grzx0913',
			'jd': 'ele-search/pages/search/search',
			'dd': 'pages/orderlist/pages/index/index',
			'fk': 'ele-evaluate-order/pages/ele-evaluate-center/ele-evaluate-center?spm=a2ogi.11834828.undefined&orderId=8044660059681823154&startTime=1702612171977'
		}
		
		let genderMapMt = {
			'hb': 'list-bg-elm',
			'jd': 'packages/index/search/search',
			'dd': 'pages/orders/orders',
			'fk': 'sub_inner_pages/evaluate-list/evaluate-list'
		}

		if (type === 'jd') {
			uni.setClipboardData({
				data: unref(orderGrabbingData).shopName,
				// success: function () {
				// 	console.log('success');
				// }
				// showToast: false
			});
		}

		if (item.platform === "elm") {
			uni.navigateToMiniProgram({
				appId: 'wxece3a9a4c82f58c9',
				path: genderMapEle[type],
				// success(res) {
				// }
			})
			// return
		}
		// 测试 打开小程序
		if (item.platform === "mt") {
			uni.navigateToMiniProgram({
				appId: 'wx2c348cf579062e56',
				path: genderMapMt[type],
				// success(res) {
				// }
			})
			// return
		}
	}
</script>

<style lang="scss" scoped>
	.orderPlace-container {
		.orderplace-title {
			padding-right: 20rpx;
		}

		.placeorder-content {
			.placeorder-title {
				font-size: 30rpx;

				.title-index {
					width: 40rpx;
					height: 40rpx;
					color: #fff;
					font-size: 20rpx;
					text-align: center;
					line-height: 40rpx;
					border-radius: 50%;
					background: $uni-color-primary;
					margin-right: 10rpx;
				}
			}
		}

		.placeorder-1-btn {
			width: 48%;
			margin: auto;
		}


		.placeorder-2-main {
			font-size: 28rpx;
			font-weight: 400;
			color: #666666;

			.placeorder-2-main-text {
				font-weight: 500;
			}
		}

		.uploading-content {
			.uploading-title-text {
				font-size: 30rpx;
				font-weight: 500;
				color: #333333;
				position: relative;
				left: 10px;
			}

			.uploading-title-text::before {
				position: absolute;
				content: "";
				width: 6px;
				height: 100%;
				background-color: #FF5046;
				top: 0px;
				left: -10px;
				border-radius: 3px;
			}

			.uploading-warn {
				font-size: 28rpx;
				font-weight: 400;
				color: #FF5C5C;
				background: #FEF4D0;
				padding: 20rpx;

				.uploading-warn-lable {
					color: #666666;
				}
			}

			.upload_imgs_img {
				width: 200rpx;
				height: 200rpx;
				border-radius: 10rpx;
			}
		}


		.time {
			align-items: center;

			&__custom {
				height: 24rpx;
				height: 24rpx;
				background-color: $uni-color-primary;
				border-radius: 4px;
				line-height: 24rpx;
				font-size: 28rpx;
				padding: 10rpx;

				&__item {
					color: #fff;
					font-size: 12px;
					text-align: center;
				}
			}

			&__doc {
				color: $uni-color-primary;
				padding: 0px 4px;
			}
		}


		.screenshot-example {
			.screenshot-example-title {
				padding: 20rpx 0;
				text-align: center;
				font-size: 32rpx;
			}

			padding: 10rpx 20rpx 20rpx 20rpx;
		}
	}
</style>